﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.ProductionManage.Plan;
using ProduceBasicData.Api.DTO.ProductionManage;
using ProduceBasicData.Domain.ProductionManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using System.Runtime;

namespace ProduceBasicData.Api.Application.Handler.ProductionManage.Plan
{
    public class Plan_SchedulingCreateCommandHandler : IRequestHandler<Plan_SchedulingCreateCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<Plan_Scheduling> planrepository;
        private readonly IMapper mapper;

        public Plan_SchedulingCreateCommandHandler(IBaseRespository<Plan_Scheduling> planrepository, IMapper mapper)
        {
            this.planrepository = planrepository;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(Plan_SchedulingCreateCommand request, CancellationToken cancellationToken)
        {
           var result=new ApiResult<int>()
           {
               Code=ApiEnum.Success,
               Msg="添加排班成功"
           };
            var info = mapper.Map<Plan_Scheduling>(request);
            var listinfo = planrepository.GetAll().FirstOrDefault(o=>Convert.ToString(o.Date)==request.Date&&o.UserId==request.UserId);
            if(listinfo!=null)
            {
                listinfo.Isdel = true;
                result.Data = await planrepository.Update(listinfo);
            }
            else
            {
                result.Data = await planrepository.AddAsync(info);
            }

            
            return await Task.FromResult(result);
           
        }
    }
}
